// ActionScript file

	private var uploadFileRefList:FileReferenceList = new FileReferenceList();
	private var uploadURL:URLRequest = new URLRequest("http://localhost:3000/application/upload_file");
	
	private function uploadFiles():void
	{
		uploadFileRefList.addEventListener(Event.SELECT, uploadSelectHandler);

		try {
    			var success:Boolean = uploadFileRefList.browse();
		} catch (error:Error) {
    			trace("Unable to browse for files. " + error);
		}
	}
	
	private function doUpload(file:FileReference):void
	{
		file.addEventListener(Event.COMPLETE, uploadCompleteHandler);
		file.addEventListener(IOErrorEvent.IO_ERROR, uploadIoErrorHandler);
		file.addEventListener(ProgressEvent.PROGRESS, uploadProgressHandler);
		
		var variables:URLVariables = new URLVariables();
	    variables.folder = "public/" + fileFolder;
	    uploadURL.data = variables;
		
		try {
	        file.upload(uploadURL);
	        
	    } catch (error:Error) {
	        trace("Unable to upload file. " + error);
	    }
		
		
	}
	
	private function uploadSelectHandler(event:Event):void
	{
		
		for each (var file:FileReference in uploadFileRefList.fileList)
			filesToUpload.addItem(file.name);
		
		
		doUpload(uploadFileRefList.fileList[0]);		
		
	}
	
	private function uploadProgressHandler (event:ProgressEvent):void
	{
		pb.label = "Uploading " + event.currentTarget.name + " " + Math.floor((event.bytesLoaded/event.bytesTotal)*100) + "% complete";
		pb.setProgress(event.bytesLoaded, event.bytesTotal);
	}
	private function uploadIoErrorHandler (event:Event):void
	{
		trace ("Upload failed: " + event);
	}
	private function uploadCompleteHandler (event:Event):void
	{
		uploadedFiles.addItem(event.currentTarget.name);
		
		filesToUpload.removeItemAt(0);
		
		uploadFileRefList.fileList.splice(0, 1);
		
		if (filesToUpload.length == 0)
		{
			pb.label = "LOADING 0%";
			pb.setProgress(0, 0);
			event.currentTarget.removeEventListener(Event.COMPLETE, uploadCompleteHandler);
			event.currentTarget.removeEventListener(IOErrorEvent.IO_ERROR, uploadIoErrorHandler);
			event.currentTarget.removeEventListener(ProgressEvent.PROGRESS, uploadProgressHandler);
		}
		else
		{
			doUpload(uploadFileRefList.fileList[0]);
		}
			
	}